package myJs

import myJs.Implicits._
import myJs.myPkg._
import myJs.myPkg.highcharts._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, Event, FormData, XMLHttpRequest, document}
import scalatags.Text.all._

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 11/5/2020
 */
@JSExportTopLevel("GeoPredict")
object GeoPredict {

  @JSExport("init")
  def init = {
    bootStrapValidator
    registerEvent
  }

  def registerEvent = {
    $(document.body).on("click", s".myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).on("change fileclear", s".file", "", (y: Element) => {
      $("#form").bv.revalidateField("file")
    })
  }

  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      val element = div(id := "content",
        span(id := "info", "Running",
          span(id := "progress")), " ",
        img(src := "/mtd/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions(title=Tool.zhInfo,closeBtn=0,skin="layui-layer-molv",btn=List())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.ToolController.geoPredict().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = Utils.progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val rs = xhr.responseText.toJDJAn
          val valid = rs("valid").toB
          layer.close(index)
          if(!valid){
            g.swal("Error", rs.myGet("message"), "error")
            $("#result").hide()
          }else{
            $("#country").text(rs.myGet("country"))
            $("#result").show()
          }
        }
      }
      xhr.send(formData)
    }
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "file" ->{
          val info="Query genome file"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${info} should not be empty!"
              ),
              "file" -> js.Dictionary(
                "message" -> "incorrect format!",
                "extension" -> "fa,fna",
              ),
            )
          )
        } ,
      )
    )

    $(s"#form").bootstrapValidator(dict)
  }

}
